﻿#region License
/*
Copyright (c) 2009, G.W. van der Vegt
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided 
that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the 
  following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and 
  the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of G.W. van der Vegt nor the names of its contributors may be 
  used to endorse or promote products derived from this software without specific prior written 
  permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
*/
#endregion License

namespace Swiss
{
    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using System.Runtime.InteropServices.ComTypes;

    /// <summary>
    /// A Stream inside an Ole32 Compound Documen.
    /// </summary>
    public class StorageStream : IDisposable
    {
        /// <summary>
        /// Exposes the content of a StorageStream as a String.
        /// </summary>
        public String Text
        {
            get
            {
                return ReadStream();
            }
            set
            {
                WriteStream(value);
            }
        }

        private Interop.IStorage fStorage;
        private StoragePath fPath;
        private string fFilename;
        private IStream fStream;

        /// <summary>
        /// Creates a StorageStream inside a Storage.
        /// </summary>
        /// <param name="aStreamName">The name of the StorageStream to create.</param>
        /// <param name="aStorage">The Storage in which to create the StorageStream.</param>
        public StorageStream(String aStreamName, Interop.IStorage aStorage)
        {
            fFilename = StoragePath.ExtractFileName(aStreamName);
            fStorage = aStorage;
            fPath = new StoragePath(aStreamName, aStorage);

            Interop.IStorage fDir = fPath.GetCD();

            if (fPath.StreamExists(fFilename))
            {
                fDir.OpenStream(
                    fFilename,
                    IntPtr.Zero,
                    Interop.STGM.READWRITE | Interop.STGM.SHARE_EXCLUSIVE,
                    0,
                    out fStream);
            }
            else
            {
                fDir.CreateStream(
                    fFilename,
                    Interop.STGM.CREATE | Interop.STGM.READWRITE | Interop.STGM.SHARE_EXCLUSIVE,
                        0,
                    0,
                    out fStream);
            }
        }

        /// <summary>
        /// Returns the size of a StorageStream.
        /// </summary>
        /// <remarks>This should be turned into a property so one can truncate a StorageStream.</remarks>
        /// <returns>The size of the StorageStream.</returns>
        public Int32 Size()
        {
            IntPtr pcbSeek = Marshal.AllocHGlobal(sizeof(Int32));

            fStream.Seek(0, (Int32)Interop.STREAM_SEEK.END, pcbSeek);
            Int32 Result = Marshal.ReadInt32(pcbSeek);

            Marshal.FreeHGlobal(pcbSeek);

            return Result;
        }

        /// <summary>
        /// Reads the stream and returns the content as a String.
        /// </summary>
        /// <remarks>Contains some disabled unsafe code.</remarks>
        /// <returns>The content of the StorageStream.</returns>
        private String ReadStream()
        {
            byte[] buffer = new byte[1024];
            Int32 readBytes = 0;
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

            #region Unsafe
            //Unsafe code..., add /Unsafe to build options.

            //unsafe
            //{
            //  fStream.Read(buffer, 1024, new System.IntPtr(&readBytes));
            //}

            #endregion

            //Safe code...
            IntPtr pcbSeek = Marshal.AllocHGlobal(sizeof(Int32));
            fStream.Seek(0, (Int32)Interop.STREAM_SEEK.SET, pcbSeek);
            Marshal.FreeHGlobal(pcbSeek);

            string Result = "";

            IntPtr pcbRead = Marshal.AllocHGlobal(sizeof(Int32));

            do
            {
                for (Int32 i = 0; i < 1024; i++)
                {
                    buffer[i] = 0;
                }
                fStream.Read(buffer, 1024, pcbRead);
                readBytes = Marshal.ReadInt32(pcbRead);

                if (readBytes != 0)
                {
                    //Be Sure to remove any trailing #0 character (D7 compatibility).
                    Int32 end = 0;
                    for (Int32 i = 0; i < 1024; i++)
                    {
                        if (buffer[i] == 0)
                        {
                            break;
                        }
                        end = i + 1;
                    }

                    Result += enc.GetString(buffer, 0, end);
                }
            } while (readBytes == 1024);

            Marshal.FreeHGlobal(pcbRead);

            return Result;
        }

        /// <summary>
        /// Overwrites the content of a StorageStream with a String.
        /// </summary>
        /// <remarks>Contains some disabled unsafe code.</remarks>
        /// <param name="value">The new content of the StorageStream.</param>
        private void WriteStream(String value)
        {
            Int32 writeBytes = 0;
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

            #region Unsafe
            //Unsafe code..., add /Unsafe to build options.

            //unsafe
            //{
            //  fStream.Write(buffer, 1024, new System.IntPtr(&writeBytes));
            //}

            #endregion

            //Safe code...
            IntPtr pcbSeek = Marshal.AllocHGlobal(sizeof(Int32));
            fStream.Seek(0, (Int32)Interop.STREAM_SEEK.SET, pcbSeek);
            Marshal.FreeHGlobal(pcbSeek);

            IntPtr pcbWritten = Marshal.AllocHGlobal(sizeof(Int32));

            byte[] buffer = enc.GetBytes(value);
            fStream.Write(buffer, value.Length, pcbWritten);
            writeBytes = Marshal.ReadInt32(pcbWritten);

            //Be Sure to add a trailing #0 character (D7 compatibility).
            buffer[0] = 0;
            fStream.Write(buffer, 1, pcbWritten);

            Marshal.FreeHGlobal(pcbWritten);

            fStream.SetSize(writeBytes + 1);
        }

        /// <summary cref="Interop.STGC.DEFAULT">
        /// Commits a StorageStream with a Interop.STGC.DEFAULT flag.
        /// </summary>
        public void Commit()
        {
            Commit(Interop.STGC.DEFAULT);
        }

        /// <summary cref="Interop.STGC">
        /// Commits a StorageStream with a user definable Interop.STGC flag.
        /// </summary>
        /// <param name="grfCommitFlags">Type of Commit.</param>
        public void Commit(Interop.STGC grfCommitFlags)
        {
            Debug.WriteLine("StorageStream.Commit()");

            Debug.Indent();
            fStream.Commit((Int32)grfCommitFlags);
            fPath.Commit(grfCommitFlags);
            Debug.Unindent();
        }

        /// <summary>
        /// Disposes a StorageStream and releases the underlying COM Object.
        /// </summary>
        public void Dispose()
        {
            Debug.WriteLine("StorageStream.Dispose()");

            //Release or else opening the same Stream twice gives an error...
            Marshal.ReleaseComObject(fStream);
            fStream = null;

            Debug.Indent();
            fPath.Dispose();
            Debug.Unindent();
        }

        #region IDisposable Members

        /// <summary>
        /// The IDisposable version of Disposes simply calls StorageStream Dispose().
        /// </summary>
        void IDisposable.Dispose()
        {
            //Call StorageStream.Dispose().
            Dispose();
        }

        #endregion
    }
}
